import os
from datetime import datetime
from typing import Dict, Any, Optional
from pathlib import Path
from ..config import UPLOAD_DIR, ALLOWED_EXTENSIONS, MAX_FILE_SIZE, PAGE_SIZE, BASE_DIR
from fastapi import UploadFile
import shutil

# 分页函数
def paginate_query(query, page: int = 1, page_size: int = PAGE_SIZE) -> Dict[str, Any]:
    """
    对数据库查询结果进行分页
    
    Args:
        query: SQLAlchemy查询对象
        page: 当前页码，默认1
        page_size: 每页大小，默认从配置中读取
    
    Returns:
        包含分页信息的字典
    """
    # 计算总记录数
    total_items = query.count()
    
    # 计算总页数
    total_pages = (total_items + page_size - 1) // page_size
    
    # 确保页码有效
    current_page = max(1, min(page, total_pages)) if total_pages > 0 else 1
    
    # 计算偏移量
    offset = (current_page - 1) * page_size
    
    # 获取当前页的数据
    items = query.offset(offset).limit(page_size).all()
    
    return {
        "items": items,
        "current_page": current_page,
        "total_pages": total_pages,
        "total_items": total_items,
        "page_size": page_size
    }

# 保存上传的图标文件
def save_uploaded_icon(file: UploadFile) -> str:
    """
    保存上传的图标文件
    
    Args:
        file: 上传的文件对象
    
    Returns:
        保存后的文件相对路径
    """
    # 不限制文件类型
    if file.filename:
        file_extension = os.path.splitext(file.filename)[1].lower()
    else:
        file_extension = ".file"  # 默认扩展名
    
    # 生成唯一文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{timestamp}{file_extension}"
    
    # 保存文件到配置的上传目录
    upload_path = BASE_DIR / UPLOAD_DIR
    file_path = upload_path / filename
    
    # 确保目录存在
    os.makedirs(upload_path, exist_ok=True)
    
    # 保存文件
    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 返回正确的相对路径，格式为/static/uploads/icons/filename
        return f"/static/uploads/icons/{filename}"
    except Exception as e:
        raise IOError(f"保存文件失败: {str(e)}")

# 删除文件
def delete_file(file_path: str) -> bool:
    """
    删除指定的文件
    
    Args:
        file_path: 文件路径（相对于项目根目录）
    
    Returns:
        删除是否成功
    """
    if not file_path or not file_path.startswith('/'):
        return False
    
    full_path = BASE_DIR / file_path[1:]  # 去掉开头的'/'
    
    if full_path.exists():
        try:
            os.remove(full_path)
            return True
        except Exception as e:
            print(f"删除文件失败 {full_path}: {str(e)}")
            return False
    return False

# 获取图标映射
def get_icon_by_type(contact_type: str) -> str:
    """
    根据联系方式类型获取对应的图标类名
    
    Args:
        contact_type: 联系方式类型
    
    Returns:
        图标类名
    """
    icon_map = {
        "微信": "neko-icon icon-wechat",
        "QQ": "neko-icon icon-qq",
        "微博": "neko-icon icon-weibo",
        "Gitee": "neko-icon icon-gitee",
        "GitHub": "neko-icon icon-github",
        "邮箱": "neko-icon icon-email",
        "音乐": "neko-icon icon-music",
        "其他": "neko-icon icon-link"
    }
    return icon_map.get(contact_type, "neko-icon icon-link")

# 不验证文件大小
def validate_file_size(file: UploadFile) -> bool:
    """
    不限制文件大小
    
    Args:
        file: 上传的文件对象
    
    Returns:
        始终返回True
    """
    # 重置文件指针到开头
    file.file.seek(0)
    return True